﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWS.SiteManager.Core.Model;
using System.IO;

namespace IWS.SiteManager.Core
{
	public class InstallHelper
	{
		public void Install(SetupInformation info)
		{
			//if database doesn't exist, it creates new schema and initalized data. 
			DBFactory.CheckDatabaseVersion(info.DBConnectionString); 

			//setup membership
			DBFactory.InstallMembership(info.MembershipDBConnectionString);

			//write the db config
			WriteDBConfig(info); //untested... 

			//Don't need to refresh the app... it seemed to work without doing that. 
			//HackRefreshApp();
			//System.Web.HttpRuntime.UnloadAppDomain(); //should force web.config reload.
		}
		public void SetupApplication(SetupInformation info)
		{
			// admin user
			System.Web.Security.Roles.CreateRole("Admins");
			System.Web.Security.Roles.CreateRole("Editors");

			System.Web.Security.MembershipCreateStatus status = System.Web.Security.MembershipCreateStatus.Success;

			//create the admin user;
			System.Web.Security.Membership.CreateUser(info.AdminUser, info.AdminPass, info.AdminEmail, null, null, true, out status);

			if (status == System.Web.Security.MembershipCreateStatus.Success)
			{
				var member = System.Web.Security.Membership.GetUser(info.AdminUser);
				if (member != null)
				{
					System.Web.Security.Roles.AddUserToRoles(info.AdminUser, new string[] { "Admins", "Editors" });
				}
			}

		}
		private void WriteDBConfig(SetupInformation info)
		{
			StringBuilder builder = new StringBuilder();

			builder.AppendLine("<connectionStrings>");
			builder.AppendLine("	<clear/>");
			builder.AppendLine("	<add name=\"SiteManagerDefault\"");
			builder.AppendLine("		connectionString=\"{0}\"");
			builder.AppendLine("		providerName=\"System.Data.SqlClient\" />");
			builder.AppendLine("	<add name=\"SiteManagerMembership\"");
			builder.AppendLine("		connectionString=\"{1}\"");
			builder.AppendLine("		providerName=\"System.Data.SqlClient\"/>");
			builder.AppendLine("</connectionStrings>");

			System.Web.HttpContext context = System.Web.HttpContext.Current;
			if (context != null && context.Server != null)
			{
				string file = context.Server.MapPath("~/db.config");
				File.WriteAllText(file, string.Format(builder.ToString(), info.DBConnectionString, info.MembershipDBConnectionString),Encoding.UTF8);
			}
		}
		private void HackRefreshApp()
		{
			//this is dumb, but in medium trust, we can reset the app by re-writing the web.config.
			string file = System.Web.HttpContext.Current.Server.MapPath("~/web.config");
			byte[] buffer = File.ReadAllBytes(file);
			File.WriteAllBytes(file, buffer);
		}
	}
}
